package com.ckf.attendance.controller;

import com.ckf.attendance.entity.Users;
import com.ckf.attendance.service.UsersService;
import com.ckf.attendance.utils.TimeUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@RestController
public class UsersController {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UsersService usersService;

    private static final String prefix = "sign_*";


    //获取打卡时间
    @RequestMapping(value = "in_time.do")
    @ResponseBody
    public String in_time() throws Exception {
        String in_time = "";
        //获取当前操作的用户
        Users user = (Users) SecurityUtils.getSubject().getPrincipal();//集成shiro
        //user类里面只需要用户id和用户名，各位自由发挥
        Users punchClock = new Users();

        punchClock.setAttendanceTime(TimeUtils.dateTime());
        punchClock.setId(user.getId());


        if(punchClock == null){

            in_time = "当前暂未打卡!";
        }else {
            in_time = TimeUtils.dateTime().format(punchClock.getPunchOutTime());
        }
        return in_time;
    }



    /**
     * 用户签到
     *
     * @param name
     * @return
     */
    @GetMapping("/sign")
    public Map userSign(String name){
        Map result = new HashMap();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = df.format(new Date());
        String redisKey = "sign_"+name+"_"+date;
        if (redisTemplate.hasKey(redisKey)){
            result.put("status",1);
            result.put("msg","你已完成签到");
            return result;
        }
        redisTemplate.opsForValue().set(redisKey,"100",60*20,TimeUnit.SECONDS);
        result.put("status",2);
        result.put("msg","签到成功");
        return result;
    }

    //上班打卡
    @RequestMapping(value = "punch_in.do")
    @ResponseBody
    public int punch_in(String loginaddress, HttpServletRequest request) throws Exception {
        //操作记录条数，初始化为0
        int resultTotal = 0;
        //获取用户IP地址
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || ip.indexOf(":") > -1) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                ip = null;
            }
        }
        //获取当前操作的用户
        Users user = (Users) SecurityUtils.getSubject().getPrincipal();
        //打卡控制
        Users punchClock = new Users();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//考勤时间格式化
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");//打卡时间格式化
        Date inTime = format.parse("09:20:00");
        Date outTime = format.parse("10:00:00");
        punchClock.setPunchIntIme(TimeUtils.dateTime());
        punchClock.setUserId(user.getUserId());
        punchClock.setDeveloperName(user.getDeveloperName());
        Date nowTime = format.parse(format.format(date));//当前时分秒
        punchClock.setAttendanceTime(TimeUtils.dateTime());
        punchClock.setUserIp(ip);
        punchClock.setLoginAddress(loginaddress);
        //先查询用户是否已经打过卡
        if ( user == null) {
            if (nowTime.before(outTime) && nowTime.after(inTime)) {//迟到

                resultTotal = -2;
            } else if (nowTime.after(outTime)) {//缺席
                resultTotal = -3;
            } else if (nowTime.before(inTime)){

            }
        }else{
            resultTotal = -4; //已经打过卡了
        }
        return resultTotal;
    }


    /**
     * 查看签到的人
     *
     * @return
     */
    @GetMapping("/find")
    public Map findSign() {
        Map result = new HashMap();
        Set lable = redisTemplate.keys(prefix);
        result.put("data", lable);
        return result;
    }

}
